﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Prism.Mvvm;
using Prism.Regions;
using ProductionLine.Models;
using ProductionLine.Modules.ShareLib.Helpers;
using ProductionLine.Modules.ShareLib.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows;

namespace ProductionLine.ViewModels {
    public partial class MainViewModel : BindableBase {

        #region 属性和字段
        //标题
        private string _title = "汽车产线SCADA系统";
        public string Title {
            get { return _title; }
            set { SetProperty(ref _title, value); }
        }
        //日志记录
        private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();

        /// <summary>
        /// 这是左侧菜单实体集合
        /// </summary>
        private  List<Menu> _menuEntities;
        public List<Menu> MenuEntities {
            get { return _menuEntities; }
            set {
                _menuEntities = value;
                SetProperty(ref _menuEntities, value);
            }
        }

        //用户信息
        private  UserSession _userSession ;
        public UserSession UserSession {
            get { return _userSession; }
            set { _userSession = value;SetProperty(ref _userSession, value); }
        }

        //区域
        private readonly IRegionManager _regionManager;

        //历史记录
        private IRegionNavigationJournal _journal;

        //plc开关
        private bool _plcConnected;
        public bool PlcConnected {
            get => _plcConnected;
            set => SetProperty(ref _plcConnected, value);
        }

        public bool _isRevise = false;

        private GlobalConfig _globalConfig;

        public GlobalConfig GlobalConfig {
            get { return _globalConfig; }
            set { _globalConfig = value; SetProperty(ref _globalConfig, value); }
        }

        private readonly PlcParam _plcParam;
        #endregion

        #region 初始化
        public MainViewModel(PlcParam plcParam,UserSession userSession,IRegionManager regionManager, IRegionNavigationJournal journal, GlobalConfig globalConfig) {
            _regionManager = regionManager;
            _journal = journal;
            _globalConfig = globalConfig;
            _plcParam = plcParam;
            _plcConnected = globalConfig.PlcConnected;
            _userSession = userSession;
            LogsUtil.Debug("MainViewModel初始化");
            //绑定到全局配置的属性变化事件,当全局配置的属性变化时,自动更新到mainViewModel中
            _globalConfig.PropertyChanged += (sender, e) => {

                if (e.PropertyName == "PlcConnected" && _isRevise == false) {
                    PlcConnected = _globalConfig.PlcConnected;
                }
            };
            Logger.Info("MainViewModel初始化成功");
            Task.Run(async () => await  InitData());//初始化数据,现在里面没有异步操作
            //不能在初始化这里默认导航首页，因为初始化的时候还没有那些区域,所以提前最好
        }

        private async Task InitData() {
            MenuEntities =  SqlSugarHelper.Db.Queryable<Menu>().ToList();
            //异步操作
        }
        #endregion

        #region 命令
        [RelayCommand]
        void Navigate(Menu menu) {
            //string s = menu.View;

            if (menu == null || string.IsNullOrEmpty(menu.View)) {
                return;
            }

            //导航 区域
            _regionManager.Regions["ContentRegion"].RequestNavigate(menu.View,
                callback => {
                    _journal = callback.Context.NavigationService.Journal;//记录导航足迹
                });

        }


        [RelayCommand]
        private void GoBack() {//后退
            if (_journal != null && _journal.CanGoBack) {
                _journal.GoBack();
            }
        }
        [RelayCommand]
        private void GoForward() {//前进
            if (_journal != null && _journal.CanGoForward) {
                _journal.GoForward();
            }
        }

        [RelayCommand]
        void SwitchStates() {//切换PLC连接状态
            _isRevise = true;
            _globalConfig.PlcConnected = !_globalConfig.PlcConnected;//直接取反
            PlcConnected = _globalConfig.PlcConnected;//切换plc状态
            _isRevise = false;

            //取反之后再看之后的操作
            if (_globalConfig.PlcConnected == false) {
                _globalConfig.Plc.ConnectClose();//断开连接
                                                 //!!!注意:不推荐,不推荐,还是自己把后台线程全关了才是正确的,不过太麻烦了,懒得写了
                _globalConfig.Plc.Dispose(); //释放资源
            } else if (_globalConfig.PlcConnected == true) {
                _globalConfig.InitPlc(); //重新连接
                _globalConfig.InitExcelsAddress();
                if (_plcParam.AutoCollect) {
                    _globalConfig.StartCollectionIndex();
                }

            }
        }
        #endregion

        /// <summary>
        /// 导航到指定区域
        /// </summary>
        /// <param name="defaultNavName">区域名称</param>
        public void SetNavigate(string defaultNavName = "IndexView") {
            _regionManager.Regions["ContentRegion"].RequestNavigate(defaultNavName,
             callback => {
                 _journal = callback.Context.NavigationService.Journal;//记录导航足迹
             });
        }

    }
}
